package com.wyz.socket.core.impl.scheduler;

import com.wyz.socket.core.api.Scheduler;
import com.wyz.socket.core.impl.Connector;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public abstract class SchedulerJob implements Runnable {
    protected final long idleTimesoutMilllsSeconds;
    protected final Connector connector;
    private volatile Scheduler scheduler;
    private volatile ScheduledFuture<?> scheduledFuture;

    protected SchedulerJob(long idleTimesOut, TimeUnit unit, Connector connector) {
        this.idleTimesoutMilllsSeconds = unit.toMillis(idleTimesOut);
        this.connector = connector;
    }

    public synchronized void scheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
        schedule(idleTimesoutMilllsSeconds);
    }

    public synchronized void unScheduler() {
        scheduler = null;
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledFuture = null;
        }
    }

    protected void schedule(long timeoutMilliSeconds) {
        if (scheduler != null) {
            scheduledFuture = this.scheduler.scheduler(this, timeoutMilliSeconds, TimeUnit.MILLISECONDS);
        }
    }
}
